<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['race:file:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['race:file:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['race:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['race:file:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="文件名" align="center" prop="fileName">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.fileName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预览地址" align="center" prop="fileUrl">
        <template #default="scope">
          <el-link type="primary" :href="scope.row.fileUrl" target="_blank">{{ scope.row.fileUrl }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="预览" align="center" prop="fileUrl">
        <template #default="scope">
            <el-image 
              style="width: 60px; height: 60px" 
              :src="scope.row.fileUrl" 
              :fit="fit" 
              @click="downloadImage(scope.row.fileUrl, scope.row.fileName)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['race:file:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['race:file:remove']">删除</el-button>
          <el-button link type="primary" icon="Pointer" @click="handleCopyUrl(scope.row.fileUrl)" v-hasPermi="['race:file:list']">复制地址</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件对话框 -->
     <!-- http://127.0.0.1:8080/common/minio/upload -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="fileRef" :model="form" :rules="rules" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="headers"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="File">
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/race/file"
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()

const fileList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const imgUrl = ref("")
// 后端上传地址（统一走代理）
const uploadAction = '/dev-api/race/minio/upload'


// 设置上传请求头
const headers = {
  Authorization: 'Bearer ' + getToken()
}

//复制URL到剪切板
const handleCopyUrl = (url) => {
  console.log('复制的URL:', url);
  
  // 创建一个临时的 textarea 元素
  const textarea = document.createElement('textarea')
  textarea.value = url
  document.body.appendChild(textarea)
  // 选中文本
  textarea.select()
  // 执行复制命令
  try {
    document.execCommand('copy')
    proxy.$modal.msgSuccess('复制成功')
  } catch (err) {
    proxy.$modal.msgError('复制失败')
  }
  // 移除临时元素
  document.body.removeChild(textarea)
}

// 添加上传相关的方法
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    imgUrl.value = response.url
    form.value.fileName = response.fileName
    form.value.fileUrl = response.url
    proxy.$modal.msgSuccess("上传成功")
  } else {
    proxy.$modal.msgError("上传失败")
  }
}

const beforeAvatarUpload = (file) => {
  // 定义允许的文件类型
  const fileTypes = ['image/jpeg', 'image/jpg', 'image/png']
  // 定义最大文件大小（2MB）
  const maxSize = 2 * 1024 * 1024

  // 检查文件类型
  if (!fileTypes.includes(file.type)) {
    proxy.$modal.msgError('图片格式必须为 JPG/PNG 格式!')
    return false
  }

  // 检查文件大小
  if (file.size > maxSize) {
    proxy.$modal.msgError('图片大小不能超过 2MB!')
    return false
  }

  return true
}
// 图片下载
const downloadImage = (url, fileName) => {
  // 创建一个a标签模拟点击下载
  const a = document.createElement('a')
  a.href = url
  a.download = fileName || 'image'
  a.click()
}
const data = reactive({
  form: {
    id: null,
    fileName: null,
    fileUrl: null,
    delFlag: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
  },
  rules: {
    fileName: [
      { required: true, message: "文件名不能为空", trigger: "blur" }
    ],
    fileUrl: [
      { required: true, message: "文件地址不能为空", trigger: "blur" }
    ],
    delFlag: [
      { required: true, message: "删除标志不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询文件列表 */
function getList() {
  loading.value = true
  listFile(queryParams.value).then(response => {
    fileList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fileName: null,
    fileUrl: null,
    delFlag: null
  }
  imgUrl.value = ""
  proxy.resetForm("fileRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加文件"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFile(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改文件"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fileRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除文件编号为"' + _ids + '"的数据项？').then(function() {
    return delFile(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('race/file/export', {
    ...queryParams.value
  }, `file_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>
